package org.example.lysh.tb.router.strategy.impl;

import org.example.lysh.tb.router.DBContextHolder;
import org.example.lysh.tb.router.DBRouterConfig;
import org.example.lysh.tb.router.strategy.IDBRouterStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liyishan
 * @date 2023/7/12 09:46
 * @apiNote
 */

public class DBRouterStrategyHashCode implements IDBRouterStrategy {
    private Logger logger = LoggerFactory.getLogger(DBRouterStrategyHashCode.class);


    private DBRouterConfig dbRouterConfig;
    public DBRouterStrategyHashCode(DBRouterConfig dbRouterConfig) {
        this.dbRouterConfig = dbRouterConfig;
    }

    /**
     * 路由计算
     *
     * @param dbKeyAttr 路由字段
     */
    @Override
    public void doRouter(String dbKeyAttr) {

        //int tbIdx = idx - dbRouterConfig.getTbCount() * (dbIdx - 1);
        int tbIdx = Integer.parseInt(dbKeyAttr);

        // 设置到 ThreadLocal；关于 ThreadLocal 的使用场景和源码介绍；https://bugstack.cn/md/java/interview/2020-09-23-%E9%9D%A2%E7%BB%8F%E6%89%8B%E5%86%8C%20%C2%B7%20%E7%AC%AC12%E7%AF%87%E3%80%8A%E9%9D%A2%E8%AF%95%E5%AE%98%EF%BC%8CThreadLocal%20%E4%BD%A0%E8%A6%81%E8%BF%99%E4%B9%88%E9%97%AE%EF%BC%8C%E6%88%91%E5%B0%B1%E6%8C%82%E4%BA%86%EF%BC%81%E3%80%8B.html
        DBContextHolder.setTBKey(String.format("%02d", tbIdx));
        logger.debug("数据库路由 tbIdx：{}", tbIdx);
    }

    @Override
    public void clear(){
        DBContextHolder.clearTBKey();
    }
}
